var model = require('../../../model/model');
var utils = require('../../../util/utils');
var logger = require('pomelo-logger').getLogger('fightRemote',__filename);
var fight = require('../handler/fightHandler');
var rooms = require('../../../model/rooms');
var common = require('../common');

var matchTime = 3*1000;//每隔多长时间执行匹配操作(毫秒)
var kickTime = 20*1000;//每隔多长时间执行踢桌操作(毫秒)
var cleanTime = 30*1000;//每隔多长时间执行清理游戏桌操作(毫秒)

var matchTimeOut = 4;//匹配超时多长后匹配机器人(秒)
var readyTimeOut = 30;//游戏桌允许不准备的最长时间(秒)
var tableTimeOut = 30*60;//游戏桌允许持续的最长时间(超过这个时间执行清桌处理)(秒)
var isMatchStart = false;
module.exports = function(app)
{
    return new fightRemote(app);
};

var fightRemote = function(app)
{
    this.app = app;
    this.sessionService = app.get('backendSessionService');
};

var handler = fightRemote.prototype;

handler.getBackendSessionByUid = function(uid,cb)
{
    var sid = common.getFrontendSid(uid);
    this.sessionService.getByUid(sid,uid,function(err,sessions)
    {
        cb(sessions?sessions[0]:null);
    })
}

var matchRobot = function(user,cb)
{
    model.getRobot(user.uid,user.actorId,function(err,res)
    {
        var now = utils.getTime();
        var robot =
        {
            'uid':res.playerId,
            'aid':res.actor.actorId,
            'isReady':1,
            'roomId':user.roomId,
            'time':now
        }
        var table =
        {
            'uid1':user,
            'uid2':robot,
            'isRobot':1
        }
        cb(table,res);
    })
}

handler.doMatch = function(cb)
{
    cb();//直接返回
    if( isMatchStart )
    {
        return;
    }
    var self = this;
    isMatchStart = true;
    console.info('match progress start');
    var route = 'onMatch';
    var match = function(roomId)
    {
        var matchingRoom = rooms.matchingRooms[roomId];
        var length = matchingRoom.length;
        if( length > 0 )
        {
            console.info("matching users:%j",matchingRoom);
            if ( 1 == length )
            {
                var user = matchingRoom[0];
                var now = utils.getTime();
                if (now > user.time + matchTimeOut)
                {
                    matchRobot(user, function (table, res)
                    {
                        rooms.removePlayer(user);
                        rooms.addTable(table);
                        self.getBackendSessionByUid(user.uid, function (session)
                        {
                            if( session )
                            {
                                session.set('table', table);
                                session.pushAll();
                            }
                            else
                            {
                                console.info("session not exist @uid:",user.uid);
                            }
                        });
                        res.isRobot = 1;
                        common.sendEvent(res, user.uid, route);
                    });
                }
            }
            else
            {
                while( matchingRoom.length > 1 )
                {
                    var player1 = matchingRoom[0];
                    var player2 = matchingRoom[1];
                    if (player1.uid == player2.uid)
                    {
                        rooms.removePlayer(player1);
                        break;
                    }
                    else
                    {
                        var table =
                        {
                            'uid1': player1,
                            'uid2': player2,
                            'isRobot': 0
                        }
                        rooms.removePlayer(player1);
                        rooms.removePlayer(player2);
                    }

                    rooms.addTable(table);
                    self.getBackendSessionByUid(player1.uid, function (session)
                    {
                        if( session )
                        {
                            session.set("table",table);
                            session.pushAll();
                        }
                        else
                        {
                            console.info("session not exist @uid:",player1.uid);
                        }
                    });

                    self.getBackendSessionByUid(player2.uid, function (session)
                    {
                        if( session )
                        {
                            session.set("table",table);
                            session.pushAll();
                        }
                        else
                        {
                            console.info("session not exist @uid:",player2.uid);
                        }
                    });
                    //把当前玩家信息发送给敌方
                    model.getFightInfo(table.uid1, function (err, res)
                    {
                        res.isRobot = 0;
                        common.sendEvent(res, table.uid2.uid, route);
                    });
                    //把敌方玩家信息发送给当前玩家
                    model.getFightInfo(table.uid2, function (err, res)
                    {
                        res.isRobot = 0;
                        common.sendEvent(res, table.uid1.uid, route);
                    });
                }
            }
        }
    }

    setInterval(function(){match(0);},matchTime);
    setInterval(function(){match(1);},matchTime);
    setInterval(function(){match(2);},matchTime);
    /*
    setInterval(function(){self.doKick(0);},kickTime);
    setInterval(function(){self.doKick(1);},kickTime);
    setInterval(function(){self.doKick(2);},kickTime);
    /*
    setInterval(function(){self.doClean(0);},cleanTime);
    setInterval(function(){self.doClean(1);},cleanTime);
    setInterval(function(){self.doClean(2);},cleanTime);
    */
}

//执行清理踢人操作
handler.doKick = function(roomId,time)
{
    var self = this;
    var room = rooms.matchedRooms[roomId];
    console.info('kick table start');
    if( room.length > 0 )
    {
        for( var i in room )
        {
            var table = room[i];
            var uid1 = table.uid1;
            var uid2 = table.uid2;
            if( !(uid1.isReady && uid2.isReady) )
            {
                var now = utils.getTime();
                if( now > table.time + readyTimeOut )//踢出超时未准备的游戏桌
                {
                    rooms.removeTable(uid1,function(table)
                    {

                    });
                    if( !uid1.isReady && !uid2.isReady )//两个都未准备
                    {
                        common.sendEvent({},uid1.uid,'onFightKick');
                        common.sendEvent({},uid2.uid,'onFightKick');
                    }
                    else
                    {
                        if( table.isRobot )
                        {
                            common.sendEvent({},uid1.uid,'onFightKick');
                        }
                        else
                        {
                            if( uid1.isReady )
                            {
                                common.sendEvent({},uid1.uid,'onLeave');
                                common.sendEvent({},uid2.uid,'onFightKick');
                                uid1.isReady = 0;
                                uid1.time = utils.getTime();
                                rooms.addPlayer(uid1);
                            }
                            else
                            {
                                common.sendEvent({},uid2.uid,'onLeave');
                                common.sendEvent({},uid1.uid,'onFightKick');
                                uid2.isReady = 0;
                                uid2.time = utils.getTime();
                                rooms.addPlayer(uid2);
                            }
                        }
                    }
                }
            }
        }
    }
}

handler.doClean = function(roomId,time)
{
    var self = this;
    var room = rooms.matchedRooms[roomId];
    console.info('clean table start');
    if ( room.length > 0 )
    {
        for( var i in room )
        {
            var table = room[i];
            var now = utils.getTime();
            if( now > table.time + tableTimeOut )//清理超时的游戏桌
            {
                rooms.removeTable(table.uid1,function(table)
                {

                });
                console.info('cleaned table:',table);
            }
        }
    }
}

handler.doRematch = function(player,cb)
{
    cb();
    var self = this;
    rooms.removeTable(player,function(table)
    {
        if( table )
        {
            player.isReady = 0;
            rooms.addPlayer(player);
            if( !table.isRobot )
            {
                var enemy = common.findEnemyByTable(player,table);
                common.sendEvent({},enemy.uid,'onLeave');
                enemy.isReady = 0;
                rooms.addPlayer(enemy);
            }
            else
            {
                console.info("table is a robot would not send onLeave msg");
            }
        }
        else
        {
            console.info("remove table error");
        }
    });
}

handler.doResult = function(player,isEscape,table,result,cb)
{
    console.info("result table:",table);
    if( table.uid1.uid )
    {
        rooms.removeTable(player,function(table)
        {

        });

        if ( !table.isRobot )
        {
            var eid = common.findEnemyByTable(player,table).uid;
            model.doResult(eid,!result,function(err,res)
            {
                if(res)
                {
                    common.sendEvent(res,eid,'onResult');
                }
            })
        }
        if( !isEscape )
        {
            model.doResult(player.uid,result,function(err,res)
            {
                if( res )
                {
                    common.sendEvent(res,player.uid,'onResult');
                }
            })
        }
    }
    cb();
}

handler.fightLeave = function(player,table,cb)
{
    cb();
    //匹配中离开
    if( player )
    {
        if( table )
        {
            rooms.removeTable(player,function(table)
            {

            });
            if( !table.isRobot )
            {
                var enemy = common.findEnemyByTable(player,table);
                enemy.time = utils.getTime();
                common.sendEvent({},enemy.uid,'onLeave');
                rooms.addPlayer(enemy);
            }
        }
        else
        {
            console.info('player not matched a enemy');
            rooms.removePlayer(player);
        }
    }
    else
    {
        console.info('player not in match room');
    }
}

handler.fightEscape = function(player,table,cb)
{
    //对战中逃跑
    console.info('uid@%d escape',player.uid);
    if( table )
    {
        if ( !table.isRobot )
        {
            var eid = common.findEnemyByTable(player,table).uid;
            common.sendEvent({},eid,'onEscape');
        }
        this.doResult(player,true,table,0,function()
        {

        });
    }
    cb();
}